package com.hsshy.beam.common.utils;

import cn.hutool.core.io.FileUtil;
import net.coobird.thumbnailator.Thumbnails;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
/**
 * @description: 图片工具类
 * @author: hs
 * @create: 2020-12-08 09:57:43
 **/
public class ImgUtil {


    public static void compress(String path) {
        List<File> fileList = FileUtil.loopFiles(path);
        try {
            for (File file : fileList) {
                String suffix = FileUtil.getSuffix(file.getName());
                // 视频不进行压缩
                if (suffix.equals("mp4") || suffix.equals("gif")) {
                    continue;
                }
                float quality = 1f;
                // 小于 100k 不进行压缩
                if (file.length() <= 100 * 1024) {
                    continue;
                } else if (file.length() <= 300 * 1024) {
                    quality = quality * 0.5f;
                } else if (file.length() <= 600 * 1024) {
                    quality = quality * 0.25f;
                } else {
                    quality = quality * 0.1f;
                }
                InputStream input = FileUtil.getInputStream(file);
                ByteArrayOutputStream output = new ByteArrayOutputStream();
                //图片尺寸不变，压缩图片文件大小outputQuality实现,参数1为最高质量
                Thumbnails.of(input).scale(1f).outputQuality(quality).toOutputStream(output);
                byte[] result = output.toByteArray();
                // 缩略图
                FileUtil.writeBytes(result, file.getPath());
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        compress("D:\\tmp\\fst\\202011\\");
    }

}
